package com.shbatis.transaction.jdbc;



import com.shbatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class JdbcTransaction implements Transaction {

    private DataSource dataSource;
    private boolean autoCommit;  // 自动提交  true自动提交  false手动提交
    /**
     * 连接对象，控制事务时需要
     */
    private Connection conn;



    public JdbcTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }


    @Override
    public void commit() {
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException("提交数据库失败");
        }
    }

    @Override
    public void rollback() {
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException("回滚数据库失败");
        }
    }

    @Override
    public void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException("关闭数据库连接失败");
        }
    }

    @Override
    public void openConnection() {
        try {
            this.conn = dataSource.getConnection();
            this.conn.setAutoCommit(autoCommit);
        } catch (Exception e) {
            throw new RuntimeException("打开数据库连接失败");
        }
    }

    @Override
    public Connection getConnection() {
        return this.conn;
    }
}

